layui.use('upload', function(){
    var $ = layui.jquery;
    var upload = layui.upload,batchUpload = layui.upload;
    var size = 1024*6;
    var img_exts = 'jpg|png|jpeg';
    img_exts += '|' + img_exts.toLocaleUpperCase();

    /** 上传单张图片 */
    upload.render({
        elem: '#slide-pc',
        url: '/finances/upload/index',
        size: size,
        auto: true,
        acceptMime: 'image/*',
        exts: img_exts,
        multiple: true,
        before: function(obj) {
            var uploadDir=$('#uploadDir').val();
            this.data = {
                name: uploadDir
            }
            var files = this.files = obj.pushFile();
            var fileName;
            var i = 0;
            var j = 0;
            for(var key in files){
                i++;
                fileName = files[key].name; //针对一个文件直接赋值就可以了
            }
            //判断队列每次只保存最后一个文件
            if(i>1){
                for(var key in files){
                    j++;
                    if(i == j){
                        fileName = files[key].name;
                    }else{
                        delete files[key]; //删除队列中的文件
                    }
                }
            }
            var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
            if(img_exts.indexOf(ext) == -1){
                layer.msg("请上传图片，或更改资源类型！");
                return false;
            }
            layer.msg('图片上传中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            })
        },
        done: function(res,index) {
            layer.close(layer.msg());//关闭上传提示窗口
            var fileName =this.files[index].name;
            var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
            var upload_dir_name=res.data.dir+random_string(10)+'.'+ext;
            var request = new FormData();
            request.append("OSSAccessKeyId",res.data.accessid);//Bucket 拥有者的Access Key Id。
            request.append("policy",res.data.policy);//policy规定了请求的表单域的合法性
            request.append("Signature",res.data.signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
            //---以上都是阿里的认证策略
            request.append("key",upload_dir_name);//文件名字，可设置路径
            request.append("success_action_status",'200');// 让服务端返回200,不然，默认会返回204
            // request.append('file', result);//需要上传的文件 file
            request.append('file',this.files[index]);
            request.append("callback",'oss-cn-hangzhou.aliyuncs.com');//回调，非必选，可以在policy中自定义
            $.ajax({
                size: size,
                type:'post',
                url : res.data.host,  //上传阿里地址
                data : request,
                processData: false,//默认true，设置为 false，不需要进行序列化处理
                cache: false,//设置为false将不会从浏览器缓存中加载请求信息
                async: false,//发送同步请求
                contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
                dataType: 'text',//不涉及跨域  写json即可
                success : function(callbackHost, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                    console.log(request);
                    if(request !='success'){
                        layer.msg("上传图片出错");return false;
                    }
                    $('#slide-pc-priview').append('<li class="item_img"><div class="operate"><i class="toleft layui-icon">' +
                        '</i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div>' +
                        '<img src=' + res.data.host+upload_dir_name+' class="img" ><input type="hidden" name="imgs[]" value="'+ res.data.host+upload_dir_name + '" /></li>');
                    res.data.full_file_name = res.data.host+upload_dir_name;
                    if( typeof uploadCallback == 'function' ) uploadCallback(res.data);
                    if( typeof setImgSize == "function" ) setImgSize($('#slide-pc-priview>.item_img>img'));
                },
                error : function(returndata) {
                    layer.msg("上传图片出错"+returndata.data);
                }
            });

        }
    });

    /** 上传多张图片 */
    var uploadKey = [],loading = null;
    batchUpload.render({
        elem: '#batch-upload-pc',
        url: '/finances/upload/index',
        size: size,
        auto: true,
        acceptMime: 'image/*',
        exts: img_exts,
        multiple: true,
        before: function(obj) {
            var uploadDir=$('#uploadDir').val();
            this.data = {
                name: uploadDir
            }

            var files = [];
            this.old_files = typeof this.old_files == "undefined" ? [] : this.old_files;// 旧文件
            this.new_files = obj.pushFile(); // 新文件
            this.files_count = 0;//成功处理文件数
            this.deal_files_count = 0;//需要处理文件数

            // var fileName;
            for(var key in this.new_files){
                //旧文件已处理
                if( typeof this.old_files[key] != "undefined" ) continue;
                this.old_files[key] = this.new_files[key];
                this.deal_files_count++;

                /*fileName = this.new_files[key].name; //针对一个文件直接赋值就可以了
                var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                if(img_exts.indexOf(ext) == -1) continue;*/

                files[key] = this.new_files[key];
                this.files_count++;
            }
            this.files = files;
            loading = layer.msg('图片上传中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            })
        },
        done: function(res,index) {
            for(var key in this.files) {
                if( $.inArray(key,uploadKey) !== -1 ) continue;
                uploadKey.push(key);

                var fileName = this.files[key].name;
                var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                var upload_dir_name = res.data.dir + random_string(10) + '.' + ext;
                var request = new FormData();
                request.append("OSSAccessKeyId", res.data.accessid);//Bucket 拥有者的Access Key Id。
                request.append("policy", res.data.policy);//policy规定了请求的表单域的合法性
                request.append("Signature", res.data.signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
                //---以上都是阿里的认证策略
                request.append("key", upload_dir_name);//文件名字，可设置路径
                request.append("success_action_status", '200');// 让服务端返回200,不然，默认会返回204
                // request.append('file', result);//需要上传的文件 file
                request.append('file', this.files[key]);
                request.append("callback", 'oss-cn-hangzhou.aliyuncs.com');//回调，非必选，可以在policy中自定义
                $.ajax({
                    size: size,
                    type: 'post',
                    url: res.data.host,  //上传阿里地址
                    data: request,
                    processData: false,//默认true，设置为 false，不需要进行序列化处理
                    cache: false,//设置为false将不会从浏览器缓存中加载请求信息
                    async: false,//发送同步请求
                    contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
                    dataType: 'text',//不涉及跨域  写json即可
                    success: function (callbackHost, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                        if (request != 'success') {
                            layer.msg("上传图片出错");return false;
                        }
                        $('#batch-upload-pc-priview').append('<li class="item_img"><div class="operate"><i class="toleft layui-icon">' +
                            '</i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div>' +
                            '<img src=' + res.data.host + upload_dir_name + ' class="img" ><input type="hidden" name="imgs[]" value="' + res.data.host + upload_dir_name + '" /></li>');
                        if(typeof setImgSize == "function") setImgSize($('#batch-upload-pc-priview>.item_img>img'));
                    },
                    error: function (returndata) {
                        layer.msg("上传图片出错" + returndata.data);
                    }
                });
            }
            //关闭上传提示窗口
            layer.close(loading);
        },
        allDone: function(obj) {
            layer.msg('成功上传'+ this.files_count+ '张图片');
        },
    });

});
//点击多图上传的X,删除当前的图片
$("body").on("click",".close",function(){
    $(this).closest("li").remove();
});
//多图上传点击<>左右移动图片
$("body").on("click",".pic-more ul li .toleft",function(){
    var li_index=$(this).closest("li").index();

    if(li_index>=1){
        $(this).closest("li").insertBefore($(this).closest("ul").find("li").eq(Number(li_index)-1));
    }
});
$("body").on("click",".pic-more ul li .toright",function(){
    var li_index=$(this).closest("li").index();
    $(this).closest("li").insertAfter($(this).closest("ul").find("li").eq(Number(li_index)+1));
});

var imgDataNext = '';//当前点击图片
//扩大图集js
$("body").on("click",".img",function(){
    imgDataNext = $(this);
    showImg($(this));
});

/**
 * 页面加载需要执行图片相关函数
 * @author:Allan
 */
$(document).ready(function () {
   if(typeof setImgSize == "function") setImgSize();
});

var swidth;
var sheight;

//左
$("body").on('click','.next-img-left',function (e) {
    var nextImg = imgDataNext.parent().prev().children('img').attr("src");
    // console.log(nextImg)
    if(nextImg){
        $('body .layui-layer-shade').trigger("click");
        showImg(imgDataNext.parent().prev().children('img'));
        imgDataNext = imgDataNext.parent().prev().children('img');
    }

});
//右
$("body").on('click','.next-img-right',function (e) {
    var nextImg = imgDataNext.parent().next().children('img').attr("src");
    // console.log(nextImg);
    if(nextImg){
        $('body .layui-layer-shade').trigger("click");
        showImg(imgDataNext.parent().next().children('img'));
        imgDataNext = imgDataNext.parent().next().children('img');
    }

});

//获取预览图片原始值
function queryImgOriginal(width,height){
    swidth =width;
    sheight =height;
}



function showImg(imgData){
    var img = new Image();

    img.src = imgData.attr("src");
    var height = img.height; // 原图片大小
    var width = img.width; //原图片大小

    var winHeight = $(window).height() - 80;  // 浏览器可视部分高度
    var winWidth = $(window).width() - 100;  // 浏览器可视部分宽度

    // 如果图片高度或者宽度大于限定的高度或者宽度则进行等比例尺寸压缩
    if (height >= winHeight || width >= winWidth) {
        // 1.原图片宽高比例 大于等于 图片框宽高比例
        if (winWidth/ winHeight <= width / height) {
            height = winWidth * (height / width);
            width = winWidth;   //以框的宽度为标准
        }

        // 2.原图片宽高比例 小于 图片框宽高比例
        if (winWidth/ winHeight > width / height) {
            width = winHeight  * (width / height);
            height = winHeight  ;   //以框的高度为标准
        }
    }
    //图片预览框可打开的 宽度和高度
    var openWidth = width,openHeight = height;
    // 图片显示大小 高度缩小50px，宽度按比例缩小
    width = openWidth * ((openHeight - 50)/openHeight);
    height = openHeight - 50;
    width = Math.ceil(width); height = Math.ceil(height);

    // console.log(width,'width')
    // console.log(height,'height')

    var imgHtml = `<div style="text-align: center;"><img src=${img.src} width='${width}px' height='${height}px' lang='h'  class="previewImg"><i class="layui-icon layui-icon-left next-img-left" style="font-size: 48px; color: #737373;position: absolute;top: 45%;left: 15px;cursor: pointer;"></i>  <i class="layui-icon layui-icon-right next-img-right" style="font-size: 48px; color: #737373;position: absolute;top: 45%;right: 15px;cursor: pointer;"></i></div>`;
    // style="transition: all 1s;-moz-transition: all 1s; -webkit-transition: all 1s; -o-transition: all 1s;"不加动画

    queryImgOriginal(width,height);

    // 打开预览 是否显示图片原始大小
    var original_size = imgData.attr("original-size");/*console.log(typeof original_size,'original size');*/
    original_size = typeof original_size == "undefined" ? true : (original_size == "true" ? true : false );
    var area = [600 + 'px',550+'px'];
    if( original_size ) area = [(openWidth < 600 ? 600 : (openWidth + 50)) + 'px',(openHeight <= 0 ? 550 : (openHeight + 50)) + 'px'];

    //弹出层
    layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        btn: ['复原','放大', '缩小','左旋转90','右旋转90','镜像','下载'],
        yes: function(index, layero){
            // 复原
            resetImg($('body').find('.previewImg'));
        },
        btn2: function(){
            //放大
            imgToSize(50,$('body').find('.previewImg'));
            return false;
        },
        btn3: function(){
            //缩小
            imgToSize(-50,$('body').find('.previewImg'));
            return false;
        },
        btn4: function(){
            //左旋转90
            imgaleft(90,$('body').find('.previewImg'));
            return false;
        },
        btn5: function(){
            //右旋转90
            imgrotate(90,$('body').find('.previewImg'));
            return false;
        },
        btn6: function(){
            //镜像
            imgReverse($('body').find('.previewImg'));
            return false;
        },
        btn7: function(){
            //下载
            getImgToBase64(img.src);
            return false;
        },
        area: area,
        // area: [width + 'px',(height + 50) + 'px'],  //原图显示,高度+50是为了去除掉滚动条
        shadeClose:true,
        scrollbar: false,
        title: "图片预览", //不显示标题
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {
            //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
        }
    })
}

var i = 0;
var rtt = 0;

//复原
function resetImg(previewImg){
    console.log(swidth)
    var img = previewImg;
    if(i > 0){
        img.width(swidth);
        img.height(sheight);
        // previewImgRecord.animate({rotate: 0}, 1000);
        previewImg.animate({},function(){
            previewImg.css({'transform':'rotate(0deg)'});
        })

        previewImg.css( {'filter' : 'fliph','-moz-transform': 'matrix(1, 0, 0, 1, 0, 0)','-webkit-transform': 'matrix(1, 0, 0, 1, 0, 0)'} );
        $("#mirror").attr('lang','h');
    }
}

/**
 *
 * @param  {[number]} size [缩减或放大多少]
 * @param  {[string]} previewImg [当前预览图片class]
 * **/
function imgToSize(size,previewImg) {
    var img = previewImg;
    var oWidth=img.width(); //取得图片的实际宽度
    var oHeight=img.height(); //取得图片的实际高度
    i++;
    img.width(oWidth + size);
    img.height(oHeight + size/oWidth*oHeight);
}
//左旋转90
function imgaleft(reg,previewImg){
    rtt = rtt - 90;
    previewImg.animate({},function(){
        previewImg.css({'transform':`rotate(${rtt}deg)`});                       
    })

    if(rtt == -360){
        rtt = 0;
    }
    i++;
}

// 右旋转90
function imgrotate(reg,previewImg){
    rtt = rtt + 90;
    previewImg.animate({},function(){
        previewImg.css({'transform':`rotate(${rtt}deg)`});
    })
    if(rtt == 360){
        rtt = 0;
    }
    i++;
}

//镜像
function imgReverse(previewImg) {
    var tar = previewImg.attr('lang');
    if (tar === 'h')
    {
        previewImg.css( {'filter' : 'fliph','-moz-transform': 'matrix(-1, 0, 0, 1, 0, 0)','-webkit-transform': 'matrix(-1, 0, 0, 1, 0, 0)'} );
        previewImg.attr('lang','fh');
    }else{
        previewImg.css( {'filter' : 'fliph','-moz-transform': 'matrix(1, 0, 0, 1, 0, 0)','-webkit-transform': 'matrix(1, 0, 0, 1, 0, 0)'} );
        previewImg.attr('lang','h');
    }
    i++;
}

/**
 * 获取图片base64
 * @param url
 * @author:Allan
 */
function getImgToBase64(url) {
    var data = {
        url:url,
    },index = null;
    $.ajax({
        url:'/finances/file/imgToBase64',
        type:       'post',
        data:       data,
        dataType:   'json',
        beforeSend: function () {
            index = layer.load(0, {shade: false});
        },
        success:    function (result) {
            layer.close(index);
            if( result.base64Url ){
                downloadImgByBase64( result.base64Url, result.filename + '.' + result.extension);
            }else{
                downloadImg(url,'');
            }
        }
    });
}

/**
 * 下载图片
 * @param url
 * @param fileName
 * @author:Allan
 */
function downloadImg(url,fileName) {
    fileName = typeof fileName == "undefined" ? '' : fileName;
    // 创建a链接
    var a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.target = "_blank";
    // 触发a链接点击事件，浏览器开始下载文件
    a.click();
}

/**
 * 根据图片base64 下载图片
 * @param url
 * @param fileName
 * @author:Allan
 */
function downloadImgByBase64(url,fileName) {
    fileName = typeof fileName == "undefined" ? '' : fileName;

    var img = new Image();
    // 必须设置，否则canvas中的内容无法转换为base64
    img.setAttribute('crossOrigin', 'Anonymous');
    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext('2d');
        // 将img中的内容画到画布上
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        // 将画布内容转换为base64
        var base64 = canvas.toDataURL();
        // 创建a链接
        var a = document.createElement('a');
        a.href = base64;
        a.download = fileName;
        // 触发a链接点击事件，浏览器开始下载文件
        a.click()
    }
    img.src = url;
}

if(typeof setImgSize != 'function'){
    /**
     * 设置图片显示大小按比例显示
     * @author:Allan
     * @param obj
     * @param winWidth
     * @param winHeight
     */
    function setImgSize(obj,winWidth,winHeight){
        obj = typeof obj != 'object' ? $('.item_img>img') : obj;
        winWidth = typeof winWidth == "undefined" ? 90 : winWidth;
        winHeight = typeof winHeight == "undefined" ? 90 : winHeight;
        obj.each(function(){
            var img = new Image(),obj =  $(this);
            img.src = obj.attr('src');
            img.onload = function(){
                var width = img.width,height = img.height;
                // console.log(width,'img width')
                // console.log(height,'img height')
                // console.log(width / height,'图片大小比例：width / height')
                // console.log(winWidth/ winHeight,'实际大小比例：winWidth/ winHeight')

                // 如果图片高度或者宽度大于限定的高度或者宽度则进行等比例尺寸压缩
                if (height >= winHeight || width >= winWidth) {
                    // 1.原图片宽高比例 大于等于 图片框宽高比例
                    if (winWidth/ winHeight <= width / height) {
                        height = winWidth * (height / width);
                        width = winWidth;   //以框的宽度为标准
                    }

                    // 2.原图片宽高比例 小于 图片框宽高比例
                    if (winWidth/ winHeight > width / height) {
                        width = winHeight  * (width / height);
                        height = winHeight  ;   //以框的高度为标准
                    }
                }
                obj.css({'width':width,'height':height,});
            }
        })
    }
}